<template>
  <a-modal
    :title="model && model.id > 0 ? '编辑' : '新增'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout" >
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="组名称">
          <a-input
            placeholder="请输入组名称"
            v-decorator="['name', {rules: [{required: true, message: '请输入组名称'}]}]" />
        </a-form-item>
        <a-form-item label="组长">
          <a-select
            showSearch
            placeholder="请选择组长"
            optionFilterProp="title"
            v-decorator="[
              'leader',
              {rules: [{ required: false, message: '请选择组长'}]}
            ]" >
            <a-select-option v-for="item in expertList" :key="item.userId" :value="item.userId" :title="item.nickName">{{ item.nickName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="组员">
          <a-select
            mode="multiple"
            showArrow
            placeholder="请选择组员"
            optionFilterProp="title"
            v-decorator="[
              'team',
              {rules: [{ required: true, message: '请选择组员'}]}
            ]" >
            <a-select-option v-for="item in expertList" :key="item.userId" :value="item.userId" :title="item.nickName">{{ item.nickName }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getSystemUser } from '@/api/consumer'
import pick from 'lodash.pick'

// 表单字段
const fields = ['id', 'name', 'leader', 'team']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      expertList: []
    }
  },
  created () {
    this.getUser()
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    getUser () {
      getSystemUser({
        size: 1000,
        current: 1,
        roleKeys: 'EXPERT'
      })
          .then(res => {
            this.expertList = res.records
          })
    }
  }
}
</script>
